import store from 'stores/configureStore';
import * as UserActions from 'actions/UserAction';

const USER_INFO = 'USER_INFO';
const TEN_MINUTE = 1000 * 60 * 10;

/**
 * 返回用户信息或者null
 */
export function getAuth() {
  try {
    const infoStr = localStorage.getItem(USER_INFO);
    if (!infoStr) return null;
    const info = JSON.parse(infoStr);
    return Date.now() < info.timestamp + TEN_MINUTE ? info : null;
  } catch (e) {
    return null;
  }
}

/**
 * 验证登陆，登陆失效清空数据
 */
export function validateAuth() {
  const info = getAuth();
  if (info) {
    store.dispatch(UserActions.saveAuth(info));
  }
  return info;
}

export function saveAuth(userInfo) {
  if (!userInfo) throw new Error('userInfo Not Found');
  userInfo.timestamp = Date.now();
  localStorage.setItem(USER_INFO, JSON.stringify(userInfo));
}

/**
 * 保存用户信息
 * @param info
 */
export function refreshAuth(info = validateAuth()) {
  if (info) {
    saveAuth(info);
  }
}

/**
 * 清空用户信息
 */
export function clear() {
  localStorage.clear();
}